package com.xjh.serverinspect.security.handler;

import com.alibaba.fastjson2.JSON;
import com.xjh.serverinspect.security.ResponseBodyHandler;
import com.xjh.serverinspect.util.ResponseDTO;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 登出成功处理
 * </p>
 *
 * @author xujinghui
 * @since 2024-12-12
 */
@Component
public class JwtLogoutSuccessHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication auth) throws IOException {
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(req, resp, auth);
        }

        resp.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = resp.getOutputStream();
        resp.setHeader("Authorization", "");

        outputStream.write(JSON.toJSONBytes(ResponseBodyHandler.encrypt(ResponseDTO.success(), req)));
        outputStream.flush();
        outputStream.close();
    }
}
